/**
 * 优惠券模块 - 可复用组件
 */
const CouponModule = {
  data() {
    return {
      coupons: [],
      isLoading: false,
      error: null
    }
  },
  methods: {
    async fetchCoupons() {
      this.isLoading = true;
      this.error = null;
      
      try {
        const response = await $.ajax({
          url: 'http://localhost:8080/user/findCouponByUserId',
          type: 'GET',
          dataType: 'json',
          headers: { 'token': `${localStorage.getItem('token') || ''}` },
          data: { userId: localStorage.getItem('userId') }
        });

        if (response.code === 200 && response.data) {
          this.coupons = response.data.map(coupon => ({
            ...coupon,
            expiryDate: coupon.expiryDate || '无限制',
            // 格式化日期
            couponEndTime: this.formatDate(coupon.couponEndTime)
          }));
        } else {
          throw new Error(response.message || '获取优惠券失败');
        }
      } catch (error) {
        console.error('获取优惠券出错:', error);
        this.error = error.message;
        this.coupons = [];
      } finally {
        this.isLoading = false;
      }
    },
    
    formatDate(dateString) {
      if (!dateString) return '无限制';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    
    getStatusClass(status) {
      return {
        0: 'status-available',
        1: 'status-used',
        2: 'status-expired'
      }[status] || '';
    },
    
    getStatusText(status) {
      return {
        0: '未使用',
        1: '已使用',
        2: '已过期'
      }[status] || '未知状态';
    },
    
    // 计算剩余天数
    getRemainingDays(endTime) {
      if (!endTime || endTime === '无限制') return '长期有效';
      
      const endDate = new Date(endTime);
      const today = new Date();
      const diffTime = endDate - today;
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      
      return diffDays > 0 ? `剩余${diffDays}天` : '已过期';
    }
  },
  created() {
    this.fetchCoupons();
  }
};

// 主Vue实例
new Vue({
  el: '#app',
  mixins: [CouponModule],
  data: {
    userAvatarUrl: '',
    username: ''
  }
});